package com.bjy.qa.agent.transport.http;

import com.bjy.qa.agent.tools.EnvCheckTool;
import com.bjy.qa.agent.tools.http.HttpHelper;
import com.bjy.qa.agent.tools.http.Params;
import com.bjy.qa.agent.tools.http.PostType;
import com.bjy.qa.agent.tools.http.Response;
import com.bjy.qa.agent.tools.json.JsonHelper;
import com.bjy.qa.agent.tools.mqtt.MqttQOS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class HttpClient {
    private final static Logger logger = LoggerFactory.getLogger(HttpClient.class);

    public static String agentKey;
    @Value("${qap.agent.key}")
    public void setAgentKey(String key) {
        HttpClient.agentKey = key;
    }

    public static String serverUrl;
    @Value("${qap.server.url}")
    public void setServerUrl(String url) {
        HttpClient.serverUrl = url;
    }

    public static String mqttUrl; // mqtt 服务器地址
    public static MqttQOS mqttQos; // mqtt 的 qos
    public static String mqttBaseTopic; // mqtt 的 BaseTopic
    public static Boolean mqttAllowAnonymous = true; // 是否允许匿名
    public static String mqttUserName; // mqtt 的用户名
    public static String mqtttPassword; // mqtt 的密码
    public static String secretKey; // 安全密钥

    /**
     * 创建 http 连接
     * @return
     */
    public static boolean init() {
        // 从服务器获得 agent 的配置信息
        Params bodyParams = new Params();
        bodyParams.add("key", agentKey);
        bodyParams.add("version", EnvCheckTool.appVersion);
        bodyParams.add("systemType", EnvCheckTool.system);
        bodyParams.add("address", EnvCheckTool.hostAddress);
        bodyParams.add("mockBaseUrl", EnvCheckTool.mockBaseURL);
        JsonHelper jsonHelper = get("/ft/agent/agentSignOn", bodyParams);
        if (jsonHelper != null) {
            HttpClient.mqttUrl = jsonHelper.getString("$.data.mqtt.url");
            HttpClient.mqttBaseTopic = jsonHelper.getString("$.data.mqtt.baseTopic");
            HttpClient.mqttQos = Enum.valueOf(MqttQOS.class, jsonHelper.getString("$.data.mqtt.qos"));
            HttpClient.mqttAllowAnonymous = jsonHelper.getBoolean("$.data.mqtt.allowAnonymous");
            HttpClient.mqttUserName = jsonHelper.getString("$.data.mqtt.userName");
            HttpClient.mqtttPassword = jsonHelper.getString("$.data.mqtt.password");
            HttpClient.secretKey = jsonHelper.getString("$.data.secretKey");
            return true;
        } else {
            return false;
        }
    }

    /**
     * 上报日志 - 接口
     * @param bodyParams 上报数据
     * @return
     */
    public static JsonHelper sendLog(Params bodyParams) {
        String uri = "/ft/testResult/log";
        return post(uri, bodyParams);
    }

    /**
     * 上报日志 - 性能
     * @param bodyParams 上报数据
     * @return
     */
    public static JsonHelper sendPerfLog(Params bodyParams) {
        String uri = "/pt/perfTestResult/log";
        return post(uri, bodyParams);
    }

    /**
     * get 请求
     * @param uri uri
     * @param bodyParams Params 类型的请求数据
     * @return
     */
    public static JsonHelper get(String uri, Params bodyParams) {
        String url = HttpClient.serverUrl + uri;
        try {
            logger.info("<-- GET: {}", url);
            logger.info("<-- {}", bodyParams);
            HttpHelper.setMediaType(PostType.JSON);
            Response response = HttpHelper.getInstance().get(url, bodyParams);
            JsonHelper jsonHelper = new JsonHelper(response.getBody());
            logger.info("--> body: {}", response.getBody().toString());

            if (response.getCode() != 200) {
                logger.error("服务器返回错误， code:{}, msg:{}", response.getCode(), response.getBody().toString());
                return null;
            }

            Integer code = jsonHelper.getInteger("$.code");
            if (code != 0) {
                logger.error("服务器返回错误， code: {}, msg: {}", code, jsonHelper);
                return null;
            }

            return jsonHelper;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * post 请求
     * @param uri uri
     * @param bodyParams Params 类型的请求数据
     * @return
     */
    public static JsonHelper post(String uri, Params bodyParams) {
        String url = HttpClient.serverUrl + uri;
        try {
            logger.info("<-- POST: {}", url);
            logger.info("<-- {}", bodyParams);
            HttpHelper.setMediaType(PostType.JSON);
            Response response = HttpHelper.getInstance().post(url, bodyParams);
            JsonHelper jsonHelper = new JsonHelper(response.getBody());
            logger.info("--> body: {}", response.getBody().toString());

            if (response.getCode() != 200) {
                logger.error("服务器返回错误， code:{}, msg:{}", response.getCode(), response.getBody().toString());
                return null;
            }

            Integer code = jsonHelper.getInteger("$.code");
            if (code != 0) {
                logger.error("服务器返回错误， code:{}, msg:{}", code, jsonHelper);
                return null;
            }

            return jsonHelper;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
